<template>
  <view class="orders">
    <!-- 已登陆时显示订单内容 -->
    <view>
      <!-- 订单状态tabs -->
      <view class="tabs">
        <view
          class="tab-item"
          :class="{ active: activeTab === index }"
          v-for="(tab, index) in tabs"
          :key="index"
          @click="changeTab(index)"
        >
          <text>{{ tab }}</text>
        </view>
      </view>

      <!-- 订单列表 -->
      <view class="order-list">
        <view v-if="orderList.length > 0">
          <!-- 订单列表 -->

          	<view 
          		class="order-item" 
          		v-for="(order, index) in orderList" 
          		:key="order.id"
          	>
          		<view class="order-header">
          			<text class="order-type">{{ order.type }}</text>
          			<text class="order-status">{{ order.status }}</text>
          		</view>
          		
          		<view class="order-time">
          			<text>{{ order.date }}</text>
          			<text>{{ order.time }}</text>
          		</view>
          		
          		<view class="order-content">
          			<view class="product-image">
          				<image :src="order.image" mode="aspectFill"></image>
          			</view>
          			<view class="product-info">
          				<text class="product-name">{{ order.productName }}</text>
          				<text class="product-price">¥{{ order.price }}</text>
          			</view>
          		</view>
          		
          		<view class="order-divider"></view>
          		
          		<view class="order-footer">
          			<text class="order-number">订单号: {{ order.orderNo }}</text>
          			<view class="order-actions">
          				<view class="action-btn" @click="orderAgain(order.id)">
          					<text>上架</text>
          				</view>
          			</view>
          		</view>
          	</view>
 
        </view>

        <!-- 空状态 -->
        <view v-else-if="!loading && pageNo === 1" class="empty-state">
          <view class="empty-icon">
            <u-icon name="order" size="80" color="#cccccc"></u-icon>
          </view>
          <text class="empty-text">~ 暂无相关数据 ~</text>
        </view>
        
        <!-- 加载中 -->
        <view v-if="loading && pageNo === 1" class="loading-state">
          <u-loading-icon></u-loading-icon>
        </view>
        
        <!-- 底部加载状态 -->
        <view v-if="orderList.length > 0" class="load-more">
          <u-loadmore :status="finished ? 'nomore' : (loading ? 'loading' : 'loadmore')" />
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// import authMixin from "@/mixins/authMixin.js";
// import orderApi from "@/api/order.js";
// import dayjs from "dayjs";

export default {
  // mixins: [authMixin],
  data() {
    return {
      activeTab: 0, // 当前选中的标签页索引
      tabs: ["全部", "鉴定中", "已完成", "已取消"], // 订单状态标签页
      // 订单状态映射
      statusMap: {
        1: "1",  // 鉴定中
        2: "2",  // 已完成
        3: "3",  // 已取消
      },
      orderList: [{
			id: 1,
			type: '订单类型',
			status: '已完成',
			date: '2025-07-07',
			time: '11:31:30',
			image: '/static/images/product-placeholder.png',
			productName: 'XXXXXX订单对象',
			price: '1950',
			orderNo: 'RC2023120100010'
		},
		{
			id: 2,
			type: '订单类型',
			status: '已完成',
			date: '2025-07-07',
			time: '11:31:30',
			image: '/static/images/product-placeholder.png',
			productName: 'XXXXXX订单对象',
			price: '1950',
			orderNo: 'RC2023120100011'
		},
		{
			id: 3,
			type: '订单类型',
			status: '已完成',
			date: '2025-07-07',
			time: '11:31:30',
			image: '/static/images/product-placeholder.png',
			productName: 'XXXXXX订单对象',
			price: '1950',
			orderNo: 'RC2023120100012'
	  }], // 订单列表
      pageNo: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0, // 总条数
      loading: false, // 加载状态
      finished: false, // 是否已加载完
      refreshing: false, // 是否正在刷新
    };
  },

  onLoad() {
    // 只有登录后才加载订单列表
    if (this.isLoggedIn) {
      //this.loadOrderList();
    }
  },

  onShow() {
    // 页面显示时检查登录状态，已登录才重新加载订单列表
    this.checkLoginStatus();
    if (this.isLoggedIn) {
      this.resetAndLoad();
    }
  },

  onReachBottom() {
    // 上拉加载更多
    if (!this.loading && !this.finished) {
      this.loadMore();
    }
  },

  methods: {
    /**
     * @description 切换订单状态标签页
     * @param {number} index - 标签页索引（0-全部，1-等待上门，2-回收中，3-已完成，4-已取消）
     */
    changeTab(index) {
      this.activeTab = index;
      this.resetAndLoad();
    },

    /**
     * @description 加载订单列表数据
     * @async
     * @returns {Promise<void>}
     */
    async loadOrderList() {
      // 未登录不请求接口
      if (!this.isLoggedIn) {
        this.loading = false;
        return;
      }
      
      if (this.loading) return;
      
      this.loading = true;
      
      try {
        // 根据activeTab获取对应的状态值
        let status = "";
        if (this.activeTab > 0) {
          status = this.statusMap[this.activeTab];
        }
        
        const res = await orderApi.getOrderList({
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          status: status
        });
        
        if (+res.code === 0) {
          const { list, total } = res.data;
          
          if (this.pageNo === 1) {
            this.orderList = list || [];
          } else {
            this.orderList = [...this.orderList, ...(list || [])];
          }
          
          this.total = total || 0;
          
          // 判断是否还有更多数据
          if (this.orderList.length >= this.total || (list && list.length < this.pageSize)) {
            this.finished = true;
          }
        } else {
          uni.showToast({
            title: res.msg || '获取订单列表失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取订单列表失败:', error);
        uni.showToast({
          title: '获取订单列表失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
        this.refreshing = false;
      }
    },
    
    /**
     * @description 重置页码并重新加载订单列表
     */
    resetAndLoad() {
      this.pageNo = 1;
      this.finished = false;
      this.orderList = [];
      //this.loadOrderList();
    },
    
    /**
     * @description 加载更多订单（分页加载）
     */
    loadMore() {
      this.pageNo++;
      //this.loadOrderList();
    },

    /**
     * @description 下拉刷新订单列表
     */
    onRefresh() {
      this.refreshing = true;
      this.resetAndLoad();
    },

    /**
     * @description 获取订单状态对应的文本描述
     * @param {string|number} status - 订单状态值
     * @returns {string} 状态文本描述
     */
    getStatusText(status) {
      const statusTextMap = {
        '1': '等待上门',
        '2': '回收中',
        '3': '已完成',
        '4': '已取消',
        1: '等待上门',
        2: '回收中',
        3: '已完成',
        4: '已取消'
      };
      return statusTextMap[status] || "未知状态";
    },
    
    /**
     * @description 获取回收类型对应的文本描述
     * @param {number} type - 回收类型值（0-旧衣，1-床单，2-玩偶，3-包包）
     * @returns {string} 回收类型文本描述
     */
    getRecycleTypeText(type) {
      // 根据recyclingType数值返回对应文本
      const typeMap = {
        0: '旧衣回收',
        1: '床单回收',
        2: '玩偶回收',
        3: '包包回收'
      };
      return typeMap[type] || '旧衣回收';
    },
    
    /**
     * @description 格式化订单时间
     * @param {string} time - 时间字符串
     * @returns {string} 格式化后的时间（YYYY-MM-DD HH:mm）
     */
    formatOrderTime(time) {
      // 使用dayjs格式化时间
      if (!time) return '--';
      return dayjs(time).format('YYYY-MM-DD HH:mm');
    },

    /**
     * @description 取消订单
     * @param {string|number} orderId - 订单ID
     * @async
     */
    cancelOrder(orderId) {
        uni.showModal({
          title: "确认取消",
          content: "确定要取消这个订单吗？",
          success: async (res) => {
            if (res.confirm) {
              // 调用取消订单API
              const res = await orderApi.cancelOrder({ id: orderId })
              if (+res.code === 0) {
                uni.showToast({
                  title: "订单已取消",
                  icon: "success",
                });
                //this.loadOrderList();
              } else {
                uni.showToast({
                  title: res.msg || "取消订单失败",
                  icon: "none",
                });
              }
            }
          },
        });
    },

    /**
     * @description 查看订单详情
     * @param {string|number} orderId - 订单ID
     */
    viewDetail(orderId) {
      uni.showToast({
        title: "开发中",
        icon: "none",
      });
    },

    /**
     * @description 删除订单
     * @param {string|number} orderId - 订单ID
     * @async
     */
    deleteOrder(orderId) {
      uni.showModal({
        title: "确认删除",
        content: "确定要删除这个订单吗？",
        success: async (res) => {
          if (res.confirm) {
            // 调用删除订单API
            const res = await orderApi.deleteOrder({ id: orderId })
            if (+res.code === 0) {
              uni.showToast({
                title: "订单已删除",
                icon: "success",
              });
              //this.loadOrderList();
            } else {
              uni.showToast({
                title: res.msg || "删除订单失败",
                icon: "none",
              });
            }
          }
        },
      });
    },

    /**
     * @description 处理登录成功事件
     */
    handleLoginSuccess() {
      // 登录成功后，重新检查登录状态
      this.checkLoginStatus();
      // 重置并加载订单列表
      this.resetAndLoad();
    },
  },
};
</script>

<style lang="scss" scoped>
.orders {
  background: #fffcf3;
  min-height: 100vh;
  display: flex;
  flex-direction: column;

  .tabs {
    display: flex;
    background: #0073C6;
    box-shadow: 0rpx 6rpx 19rpx 0rpx rgba(0, 0, 0, 0.15);
    border-radius: 0rpx 0rpx 0rpx 0rpx;
    padding: 0 38rpx;

    .tab-item {
      flex: 1;
      text-align: center;
      padding: 22rpx 0;
      position: relative;

      text {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 27rpx;
        color: #AEE4FF;
      }

      &.active {
        text {
          font-family: PingFang SC, PingFang SC;
          font-weight: bold;
          font-size: 34rpx;
          color: #FFFFFF;
        }

        &::after {
          content: "";
          position: absolute;
          bottom: 14rpx;
          left: 50%;
          transform: translateX(-50%);
          z-index: 1;
          width: 78rpx;
          height: 13rpx;
          background: url("https://lvyi.ink/admin-api/infra/file/4/get/20250707/E90LY3_1751876252473.png") no-repeat
            center center;
          background-size: 100% 100%;
        }
      }
    }
  }

	/* 订单列表 */
	.order-list {
		padding: 20rpx;
	}

	.order-item {
		background-color: #fff;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	/* 订单头部 */
	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.order-type {
		font-size: 28rpx;
		color: #4a90e2;
		font-weight: 500;
	}

	.order-status {
		font-size: 28rpx;
		color: #999;
	}

	/* 订单时间 */
	.order-time {
		display: flex;
		gap: 20rpx;
		margin-bottom: 20rpx;
	}

	.order-time text {
		font-size: 24rpx;
		color: #666;
	}

	/* 订单内容 */
	.order-content {
		display: flex;
		align-items: center;
		gap: 20rpx;
		margin-bottom: 20rpx;
	}
	.product-image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 12rpx;
		overflow: hidden;
		background-color: #f0f0f0;
	}
	
	.product-image image {
		width: 100%;
		height: 100%;
	}
	
	.product-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 10rpx;
	}
	
	.product-name {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
	}
	
	.product-price {
		font-size: 32rpx;
		color: #ff4757;
		font-weight: bold;
	}
	/* 订单底部 */
	.order-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.order-number {
		font-size: 24rpx;
		color: #999;
	}
	
	.order-actions {
		display: flex;
		gap: 20rpx;
	}
	
	.action-btn {
		background-color: #4a90e2;
		color: #fff;
		padding: 12rpx 24rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		transition: all 0.3s ease;
	}
	
	.action-btn:active {
		transform: scale(0.95);
		background-color: #3a7bc8;
	}
	
}
</style>
